package com.finance.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.CardRecharge;
import com.finance.mapper.CardRechargeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C04
 */
@Slf4j
@Service
public class CardRechargeService extends ServiceImpl<CardRechargeMapper, CardRecharge> {

    /**
     * 处理卡充值数据
     *
     * @param records CSV数据记录
     * @param searchDate 数据所属日期
     * @param forceUpdate 是否强制更新
     * @return 处理成功的记录数
     */
    @Transactional
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate) {
        return processOrders(records, searchDate, forceUpdate, null);
    }

    /**
     * 处理卡充值数据
     *
     * @param records CSV数据记录
     * @param searchDate 数据所属日期
     * @param forceUpdate 是否强制更新
     * @param cinemaId 影院ID
     * @return 处理成功的记录数
     */
    @Transactional
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            log.warn("No records to process");
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(CardRecharge::getSearchDate, searchDate)
                .eq(CardRecharge::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C04数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                .eq(CardRecharge::getSearchDate, searchDate)
                .eq(CardRecharge::getCinemaId, cinemaId)
                .remove();
        }

        log.info("Processing {} card recharge records", records.size());
        List<CardRecharge> list = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                CardRecharge cardRecharge = new CardRecharge();
                
                // 设置影院ID
                cardRecharge.setCinemaId(cinemaId);
                //充值/续费日期,充值/续费影院名称,充值/续费影院编码,充值/续费影院所属区域,订单号,卡号,卡类型编码
                // 转换日期时间
                String rechargeDate = record.get("充值/续费日期");
                if (rechargeDate != null && !rechargeDate.isEmpty()) {
                    cardRecharge.setRechargeTime(LocalDateTime.parse(rechargeDate,
                            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                cardRecharge.setCinemaName(record.get("充值/续费影院名称"));
                cardRecharge.setCinemaCode(record.get("充值/续费影院编码"));
                cardRecharge.setCinemaArea(record.get("充值/续费影院所属区域"));
                cardRecharge.setOrderNo(record.get("订单号"));
                cardRecharge.setCardNo(record.get("卡号"));
                cardRecharge.setCardTypeCode(record.get("卡类型编码"));
                // 卡类型,卡政策编码,卡政策,充值金额,销售方式,发卡面值,支付后卡余额,支付工具编码,支付工具,支付渠道
                cardRecharge.setCardType(record.get("卡类型"));
                cardRecharge.setCardPolicyCode(record.get("卡政策编码"));
                cardRecharge.setCardPolicy(record.get("卡政策"));
                // 转换金额字段
                String rechargeAmount = record.get("充值金额");
                if (rechargeAmount != null && !rechargeAmount.isEmpty()) {
                    cardRecharge.setRechargeAmount(Long.parseLong(rechargeAmount));
                }
                cardRecharge.setSalesMethod(record.get("销售方式"));
                String cardFaceValue = record.get("发卡面值");
                if (cardFaceValue != null && !cardFaceValue.isEmpty()) {
                    cardRecharge.setCardFaceValue(Long.parseLong(cardFaceValue));
                }
                String cardBalance = record.get("支付后卡余额");
                if (cardBalance != null && !cardBalance.isEmpty()) {
                    cardRecharge.setCardBalance(Long.parseLong(cardBalance));
                }
                cardRecharge.setPaymentToolCode(record.get("支付工具编码"));
                cardRecharge.setPaymentTool(record.get("支付工具"));
                cardRecharge.setPaymentChannel(record.get("支付渠道"));
                // 支付渠道编码,操作员,操作员编码,发卡影院名称,发卡影院编码,发卡影城所属区域,类型,发卡影城所属区域编码
                cardRecharge.setPaymentChannelCode(record.get("支付渠道编码"));
                cardRecharge.setOperator(record.get("操作员"));
                cardRecharge.setOperatorCode(record.get("操作员编码"));
                cardRecharge.setIssuingCinemaName(record.get("发卡影院名称"));
                cardRecharge.setIssuingCinemaCode(record.get("发卡影院编码"));
                cardRecharge.setIssuingCinemaArea(record.get("发卡影城所属区域"));
                // 转换type字段
                String typeStr = record.get("类型");
                if (typeStr != null && !typeStr.isEmpty()) {
                    try {
                        cardRecharge.setType(Integer.parseInt(typeStr));
                    } catch (NumberFormatException e) {
                        log.error("Failed to parse type value: {}", typeStr, e);
                        throw new RuntimeException("Failed to parse type value", e);
                    }
                }
                cardRecharge.setIssuingCinemaAreaCode(record.get("发卡影城所属区域编码"));
                // 充值/续费影城所属区域编码,会员ID,商户订单号,第三方支付流水号
                cardRecharge.setRechargeCinemaAreaCode(record.get("充值/续费影城所属区域编码"));
                cardRecharge.setMemberId(record.get("会员ID"));
                cardRecharge.setMerchantOrderNo(record.get("商户订单号"));
                cardRecharge.setThirdPartyPaymentNo(record.get("第三方支付流水号"));
                // 设置searchDate
                cardRecharge.setSearchDate(searchDate);
                // 设置流向客户信息
                cardRecharge.setFlowCustomerName(record.get("流向客户名称"));
                cardRecharge.setFlowCustomerCode(record.get("流向客户外部编码"));

                list.add(cardRecharge);
            } catch (Exception e) {
                log.error("Failed to process card recharge record: {}", record, e);
                throw new RuntimeException("Failed to process card recharge record", e);
            }
        }
        if (!list.isEmpty()) {
            return saveBatch(list) ? list.size() : 0;
        }
        log.info("Successfully processed {} card recharge records", records.size());
        return 0;
    }
} 